from fastapi import Request
from fastapi.responses import JSONResponse
from .exceptions import CustomException
from schemas.response import ResponseModel
from pydantic import ValidationError

async def exception_handler(request: Request, exc: Exception) -> JSONResponse:
    if isinstance(exc, CustomException):
        return JSONResponse(
            status_code=exc.status_code,
            content=ResponseModel(code=exc.code, message=exc.message).model_dump()
        )
    
    if isinstance(exc, ValidationError):
        return JSONResponse(
            status_code=200,
            content=ResponseModel(code=400, message=str(exc)).model_dump()
        )
        
    # 处理其他未知异常
    return JSONResponse(
        status_code=500,
        content=ResponseModel(code=500, message="服务器内部错误").model_dump()
    ) 